import { observer } from 'mobx-react-lite';
import Navbar from '@/components/Navbar';
import reportStore from '@/stores/ReportStore';
import { ReportEntity } from '@/entities/ReportEntity';
import { Image, Text, View } from '@tarojs/components';
import Forbid from '@/static/images/icon/forbid.png';
import ReportCard from '@/components/ReportCard';
import systemStore from '@/stores/SystemStore';
import './index.less';
import ButtonComp from '@/components/Button';
import { useEffect, useState } from 'react';
import AlterComp from '@/components/Alter';
import BusinessConstant from '@/constant/BusinessConstant';
import HouseReportBusiness from '@/business/HouseReportBusiness';
import useReport from '@/hooks/useReport';
import userStore from '@/stores/UserStore';
import socketStore from '@/stores/SocketStore';
import AuthConstant from '@/constant/AuthConstant';
import HouseBusiness from '@/business/HouseBusiness';

function LandlordReport() {
  const {getReportByLandlordId} = useReport();
  const {landlordReportList} = reportStore;
  const {user} = userStore;
  const {websocketInstance} = socketStore;
  const [reportCompletePopupVisible, setReportCompletePopupVisible] = useState(false);
  const [reportId, setReportId] = useState(0);
  const [reportStatus, setReportStatus] = useState(BusinessConstant.REPORT_PENDING);
  // 报修的租客id
  const [reportTenantId, setReportTenantId] = useState(0);
  const [houseList, setHouseList] = useState<any[]>();
  /**
   * 通过房屋id获取房屋列表
   */
  const getHouseListByHouseId = async () => {
    if (landlordReportList?.length) {
      const houseIdArr = landlordReportList?.map(t => t.houseId);
      const res: any = await HouseBusiness.getHouseListByHouseId([...new Set(houseIdArr)].join(','));
      setHouseList(res);
    }
  };

  useEffect(() => {
    getHouseListByHouseId();
  }, []);

  /**
   * 显示提示框
   * @param reportId 维修id
   * @param status 状态
   */
  const showAlterComponent = (reportId: number, status: number, tenantId: number) => {
    setReportId(reportId);
    setReportStatus(status);
    setReportTenantId(tenantId);
    setReportCompletePopupVisible(true);
  };

  /**
   * 处理已维修完成事件
   */
  const handleReportComplete = async () => {
    // 更改该维修记录的状态
    await HouseReportBusiness.updateReportStatus(reportId, reportStatus);
    // 获取房东报修记录
    await getReportByLandlordId(user?.id);
    // 向租客发送已处理的维修消息
    websocketInstance && websocketInstance.send({
      data: JSON.stringify({
        toIdentity: AuthConstant.TENANT,
        toId: reportTenantId,
        active: BusinessConstant.SOCKET_GET_TENANT_REPORT
      })
    });
    setReportCompletePopupVisible(false);
  };

  return (
    <Navbar
      mode='back'
      title='房屋维修'
      bgColor='var(--mini-first)'
    >
      <View className='landlord-report-container' style={ {height: systemStore.haveNavbarNotTabbarHeight} }>
        {
          landlordReportList?.length ?
            landlordReportList?.map((report: ReportEntity.IReport, idx: number) => {
              // 获取当前条目的房屋名称
              const houseName = houseList?.find(h => h.id === report.houseId)?.name;

              return <ReportCard
                key={ idx }
                houseName={ houseName }
                status={ report.status }
                reason={ report.reason }
                createdAt={ report.createdAt }
                updatedAt={ report.updatedAt }
                images={ JSON.parse(report.image) }
                video={ report.video }
                isSlot={ !report.status }
                FooterSlotComp={
                  <View className='report-complete'>
                    <ButtonComp
                      title='已完成维修'
                      onClick={ () => showAlterComponent(report.id, BusinessConstant.REPORT_COMPLETE, report.tenantId) }
                    />
                  </View>
                }
              />;
            }) :
            (
              <View className='no-report-application'>
                <Image src={ Forbid } className='forbid-icon'/>
                <Text>暂无维修记录</Text>
              </View>
            )
        }
      </View>
      <AlterComp
        visible={ reportCompletePopupVisible }
        onClose={ () => setReportCompletePopupVisible(false) }
        onConfirm={ handleReportComplete }
        content='该报修申请确定已维修完成吗？'/>
    </Navbar>
  );
}

export default observer(LandlordReport);